package proyecto.testcasetool.presentation.details;


import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.AbstractFormPart;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IPartSelectionListener;
import org.eclipse.ui.forms.widgets.FormToolkit;

import proyecto.testcasetool.presentation.editor.pages.FormLayoutFactory;


public abstract class DetailsPage extends AbstractFormPart implements IDetailsPage, IPartSelectionListener/*, IPropertiesEditionListener*/ {

	protected FormToolkit toolkit;

	protected EditingDomain editingDomain;

	protected EObject eObject;

	protected AdapterFactory adapterFactory;

	public DetailsPage(FormToolkit toolkit, EditingDomain editingDomain, AdapterFactory adapterFactory) {
		super();
		this.toolkit = toolkit;
		this.editingDomain = editingDomain;
		this.adapterFactory = adapterFactory;
	}

	public void createContents(Composite parent) {
		toolkit = getManagedForm().getToolkit();
		parent.setLayout(FormLayoutFactory.createDetailsGridLayout(false, 1));
		parent.setLayoutData(new GridData(GridData.FILL_BOTH));	
		
		createDetailsSection(parent);
		
	}

	public void selectionChanged(IFormPart part, ISelection selection) {
		// controlar que sea la part que esto esperando!!!!
		if (!(selection instanceof IStructuredSelection)) {
			return;
		}
		EObject newEObject = getEObjectFromSelection(selection);
		if (newEObject != null && newEObject != eObject) {
			eObject = newEObject;
			if (eObject != null) {
				System.out.println("DetailsPage.selectionChanged"+
						"\n"+part+"\n"+selection);
			}
		}
	}

	protected EObject getEObjectFromSelection(ISelection selection) {
		if (selection instanceof StructuredSelection
				&& (((StructuredSelection)selection).getFirstElement() instanceof EObject))
			return (EObject)((StructuredSelection)selection).getFirstElement();
		if (selection instanceof EObject)
			return (EObject)selection;
		if (selection instanceof IAdaptable && ((IAdaptable)selection).getAdapter(EObject.class) != null)
			return (EObject)((IAdaptable)selection).getAdapter(EObject.class);

		return null;
	}


	protected abstract void createDetailsSection(Composite parent);
	
}
